package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

/**
 * @author zhangbaiyan
 * @date 2024-09-10 11:27
 * @description:
 * @version:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {
    @Override
    public void deductBalance(Long id, Integer money) {
        //1.查询用户
        User user = getById(id);
        //2.校验用户状态
        if(user == null ||user.getStatus()==UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
        //3.校验余额是否充足
        if(user.getBalance()<money){
            throw new RuntimeException("用户余额不足");
        }
        //4.扣减余额
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance,remainBalance)
                .set(remainBalance==0,User::getStatus,2)
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance())
                .update();



    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAddressById(Long id) {
        //1.查询用户
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
        //2.查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id).list();
        //3.1封装VO
        UserVO userVo = BeanUtil.copyProperties(user, UserVO.class);
        //3.2转地址VO
        if(CollUtil.isNotEmpty(addresses)){
            userVo.setAddressList(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVo;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }
        //2.查询地址
        //2.1 获取用户id 集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2 根据用户id查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, userIds).list();
        //2.3转换地址vo
        List<AddressVO> addressVos = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4 用户地址集合分组处理,相同用户放入一个集合(组)中
       Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
       if (CollUtil.isNotEmpty(addressVos)){
           addressMap = addressVos.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
       }

       //3.转换Vo返回
        List<UserVO> list = BeanUtil.copyToList(users, UserVO.class);
       for (User user : users){
           //3.1转换User的 PO为Vo
           UserVO userVo = BeanUtil.copyProperties(user, UserVO.class);
           list.add(userVo);
           //3.2转换地址vo
           userVo.setAddressList(addressMap.get(user.getId()));
       }
        return list;
    }

    @Override
    public PageDTO<UserVO> queryUsersByPage(UserQuery query) {
        String name = query.getName();
        Integer status = query.getStatus();
        //1.构建分页条件
        Page<User> page = query.toMpPageDefaultSortCreateTime();
        //2.分页查询
        Page<User> userPage = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //3.封装VBO结果
        return PageDTO.of(userPage, User -> {
            //拷贝基础属性
            UserVO vo = BeanUtil.copyProperties(User, UserVO.class);
            //2.处理特殊逻辑
            vo.setUsername(vo.getUsername().substring(0,vo.getUsername().length() - 2)+ "***");
            return vo;
        });

    }
}
